$(function () {
    //调用获取所有地址
    window.getAllAddress();
});
//需要传过来或者从localStorage中获取用户id
var userId=localStorage.getItem("userId");
//新增/编辑地址，点击弹窗效果,省市区选择功能
function addressPop(elem) {
    layer.open({
        type: 1,
        title: false,
        shadeClose: true,
        closeBtn:0,
        shade: 0.7,
        maxmin: false, //开启最大化最小化按钮
        area: ['7.1rem', '5.5rem'],
        content: $("#popContent").html(),
        success:function () {
            //设置编辑的内容
            var addressItem=$(elem).parent(".setAddress").parent(".addressItem");
            if(elem){
                var accepterName=addressItem.attr("data-accepterName");
                var mobile=addressItem.attr("data-mobile");
                var area=addressItem.attr("data-area");
                var address=addressItem.attr("data-address");
                var addressId=addressItem.attr("data-addressId");
                var isDefault=addressItem.attr("data-isDefault");
                $(".layui-layer-content").find(".popContent").find(".name").find("#accepter_name").val(accepterName);
                $(".layui-layer-content").find(".popContent").find(".tel").find("#mobile").val(mobile);
                $(".layui-layer-content").find(".popContent").find(".chooseAd").find("#district").text(area);
                $(".layui-layer-content").find(".popContent").find(".chooseDet").find("#detailAdd").val(address);
                //添加编辑标识
                $(".layui-layer-content").find(".saveBtn").attr("data-edit",true);
                $(".layui-layer-content").find(".saveBtn").attr("data-addressId",addressId);
                $(".layui-layer-content").find(".saveBtn").attr("data-isDefault",isDefault);
            }
            //编辑和新增共用的参数
            var province=addressItem.attr("data-province");
            var city=addressItem.attr("data-city");
            var country=addressItem.attr("data-country");
            $(".layui-layer-content").find(".saveBtn").attr({
                "data-province":province,
                "data-city":city,
                "data-country":country
            });
            // 选择三级地址
            $(".chooseAd > #district").bind("click",function () {
                var layerIndex=$(".layui-layer-shade").css("zIndex");
                $(".layui-layer-shade").css("opacity","0");
                $("body > .maskContain").css({
                    "display":"block",
                    "zIndex":layerIndex+"0"
                });
                $(".btn_close").click(function () {
                    $(".maskContain").hide();
                    $(".layui-layer-shade").css("opacity","0.7");
                });
                $.ajax({
                    url:"http://api.qujiamall.com/Base/GetAreaList",
                    type:"get",
                    dataType:"json",
                    async:false,
                    success:function(data){
                    console.log(data.data);
                    var shengStr= '';
                    $.each(allData,function (index,elem) {
                        shengStr += "<li onclick='clChoItem(this)' data-level='1' data-areaId='"+elem.area_id+"' data-index='"+index+"' data-name='"+elem.name+"'>"+elem.name+"</li>";
                    });
                    $(".showContain>ul").html(shengStr);
                        allData=data.data;
                    }
                })
            })
        }
    });
}
//获取所有地址
function getAllAddress() {
    // var timestamp = Math.round(new Date().getTime()/1000);
    // // var timestamp = "1530088389";
    // var user_id = "100017";
    // // var nonce = Math.random().toString(36).substr(6);
    // var nonce = "123abc";
    // var version = "1.0";
    // var token = "bb7b4aa7-1708-435c-96a3-45fe349f3be8";
    // var str=timestamp+nonce+user_id+version+token+"user_id"+user_id;
    // //测试数据
    // // str="1530154432216 551216 100005 1 5247ea1f-01d2-4063-a9fd-0655465b8735 user_id100005";
    // var signature = str.MD5(32);
    // signature = signature.toUpperCase();
    $.ajax({
        url:'http://api.qujiamall.com/User/GetAddressList?user_id='+userId,
        type:'get',
        dataType:'json',
        async:'false',
        success:function (json) {
            console.log(json);
            var addHtml = Handlebars.compile($("#addItemContain").html());
            $('.addItemContain').html(addHtml(json));
        }
    });
}
//三级地址选择函数
function clChoItem(that) {
    var level = $(that).attr("data-level");
    var areaId= $(that).attr("data-areaId");
    var index = $(that).attr("data-index");
    var name=$(that).attr("data-name");
    $(that).css("color","#ff0036");
    if(level=="1"){
        $(".sheng").text(name).css({
            "color":"#333",
            "border-bottom":"none"
        });
        $(".sheng").attr("data-index",index).attr("data-areaId",areaId);
        $(".shi").css("display","block");
        var shiStr='';
        $.each(allData[index].sub_areas,function (index,elem) {
            shiStr+="<li onclick='clChoItem(this)' data-level='2' data-areaId='"+elem.area_id+"' data-index='"+index+"' data-name='"+elem.name+"'>"+elem.name+"</li>";
        });
        //延迟添加(模拟请求加载)
        setTimeout(function () {
            $(".showContain>ul").html(shiStr);
        },500);
    }else if(level=="2"){
        var levelId = $(that).attr("data-areaId");
        $(".shi").text(name).css({
            "color":"#333",
            "border-bottom":"none"
        });
        $(".shi").attr("data-areaId",levelId);
        var quStr='';
        //已经选省index
        var nextSheng=$(".sheng").attr("data-index");
        //本省的市数组
        var nextShi=allData[nextSheng].sub_areas;
        //本省本市下的区数组
        var nextQu=null;
        if(nextShi.length){
            $.each(nextShi,function (index,elem) {
                if(elem.area_id==levelId){
                    nextQu=elem.sub_areas;
                }
            });
        }
        if(nextQu){
            //有下一级
            $.each(nextQu,function (index,elem) {
                quStr+="<li onclick='clChoItem(this)' data-level='3' data-areaId='"+elem.area_id+"' data-index='"+index+"' data-name='"+elem.name+"'>"+elem.name+"</li>";
            });
            $(".qu").css("display","block");
            //延迟添加(模拟请求加载)
            setTimeout(function () {
                $(".showContain>ul").html(quStr);
            },500);
        }else {
            //没有下一级
            $(".shi").text(name).css({
                "color":"#ff0036",
                "border-bottom":"2px solid #ff0036"
            });
            $(that).siblings().css("color","#333");
            //关闭选择弹窗
            setTimeout(function () {
                $(".maskContain").hide();
                $(".layui-layer-shade").css("opacity","0.7");
            },500);
            // 取出所选地区
            var shengObj={name:$(".sheng").text(),id:$(".sheng").attr("data-areaId")};
            var shiObj={name:$(".shi").text(),id:$(".shi").attr("data-areaId")};
            $(".layui-layer-content #district").html(shengObj.name+","+shiObj.name).attr({
                "data-shengId":shengObj.id,
                "data-shiId":shiObj.id,
                "data-area":shengObj.name+","+shiObj.name
            });
        }
    }else if(level=="3"){
        var levelId = $(".shi").attr("data-areaId");
        $(".qu").text(name).css({
            "color":"#333",
            "border-bottom":"none"
        });
        $(".qu").attr("data-areaId",areaId);
        //已经选省index
        var nextSheng=$(".sheng").attr("data-index");
        //本省的市数组
        var nextShi=allData[nextSheng].sub_areas;
        //本省本市下的区数组
        var nextQu=null;
        if(nextShi.length){
            $.each(nextShi,function (index,elem) {
                if(elem.area_id==levelId){
                    nextQu=elem.sub_areas;
                }
            });
        }
        //本省本市本区的id
        var quId=$(".qu").attr("data-areaId");
        $.each(nextQu,function (index,elem) {
            if(elem.area_id==quId){
                if(elem.sub_areas){
                    //有下一级
                    $(".xian").css("display","block");
                }else {
                    //没有下一级
                    $(".qu").text(name).css({
                        "color":"#ff0036",
                        "border-bottom":"2px solid #ff0036"
                    });
                    $(that).siblings().css("color","#333");
                    //关闭选择弹窗
                    setTimeout(function () {
                        $(".maskContain").hide();
                        $(".layui-layer-shade").css("opacity","0.7");
                    },500);
                    // 取出所选地区
                    var shengObj={name:$(".sheng").text(),id:$(".sheng").attr("data-areaId")};
                    var shiObj={name:$(".shi").text(),id:$(".shi").attr("data-areaId")};
                    var quObj={name:$(".qu").text(),id:$(".qu").attr("data-areaId")};
                    $(".layui-layer-content #district").html(shengObj.name+","+shiObj.name+","+quObj.name).attr({
                        "data-shengId":shengObj.id,
                        "data-shiId":shiObj.id,
                        "data-quId":quObj.id,
                        "data-area":shengObj.name+","+shiObj.name+","+quObj.name
                    });
                }
            }
        });
    }
}
//三级地址头部选择函数
function clChoTop(elem) {
    var levelClass = $(elem).attr("class");
    if(levelClass.indexOf("sheng") > 0){
        $(".qu").css("display","none");
        $(".xian").css("display","none");
        $(".shi").text("请选择").css({
            "color":"#ff0036",
            "border-bottom":"2px solid #ff0036"
        });

        var shengStr= '';
        $.each(allData,function (index,elem) {
            shengStr += "<li onclick='clChoItem(this)' data-level='1' data-areaId='"+elem.area_id+"' data-index='"+index+"' data-name='"+elem.name+"'>"+elem.name+"</li>";
        });
        $(".showContain>ul").html(shengStr);
    }

    if(levelClass.indexOf("shi") > 0) {
        $(".xian").css("display", "none");
        $(".qu").text("请选择").css({
            "color": "#ff0036",
            "border-bottom": "2px solid #ff0036"
        });

        var index = $(".sheng").attr("data-index");
        var shiStr = '';
        $.each(allData[index].sub_areas, function (index, elem) {
            shiStr += "<li onclick='clChoItem(this)' data-level='2' data-areaId='" + elem.area_id + "' data-index='" + index + "' data-name='" + elem.name + "'>" + elem.name + "</li>";
        });
        $(".showContain>ul").html(shiStr);
    }
}
//新增/编辑收货地址(保存地址)
function saveAdd() {
    //获取发送的参数
    var accepter_name = $(".layui-layer-content").find("#accepter_name").val();
    var mobile = $(".layui-layer-content").find("#mobile").val();
    var detailAdd = $(".layui-layer-content").find("#detailAdd").val();
    var area = $(".layui-layer-content").find("#district").attr("data-area");
    var editOr=$(".layui-layer-content").find(".saveBtn").attr("data-edit");
    var addressId=$(".layui-layer-content").find(".saveBtn").attr("data-addressId");
    var isDefault=$(".layui-layer-content").find(".saveBtn").attr("data-isDefault");
    var province=$(".layui-layer-content").find(".saveBtn").attr("data-province");
    var city=$(".layui-layer-content").find(".saveBtn").attr("data-city");
    var country=$(".layui-layer-content").find(".saveBtn").attr("data-country");
    //从localStorage获取用户id

    if(editOr){
        $.ajax({
            url:'http://api.qujiamall.com/User/UpdateAddress',
            data:{
                'address_id':addressId,
                'accepter_name':accepter_name,
                'province':province,
                'city':city,
                'county':country,
                'area':area,
                'address':detailAdd,
                'mobile':mobile,
                'is_default':isDefault?isDefault:false,
                'user_id':userId
            },
            type:'post',
            dataType:'json',
            async:'true',
            success:function (json) {
                layer.closeAll();
                setTimeout(function () {
                    layer.msg(json.msg);
                    //重新请求所有地址刷新
                    window.getAllAddress();
                },500);
            },
            error:function (json) {
                layer.msg("添加出错~");
            }
        });
    }else {
        $.ajax({
            url:'http://api.qujiamall.com/User/AddAddress',
            data:{
                'accepter_name':accepter_name,
                'province':province,
                'city':city,
                'county':country,
                'area':area,
                'address':detailAdd,
                'mobile':mobile,
                'is_default':false,
                'user_id':userId
            },
            type:'post',
            dataType:'json',
            async:'true',
            success:function (json) {
                layer.closeAll();
                setTimeout(function () {
                    layer.msg(json.msg);
                    //重新请求所有地址刷新
                    window.getAllAddress();
                },500);
            },
            error:function (json) {
                layer.msg("添加出错~");
            }
        });
    }
}
//设置默认地址
function setDefault(elem) {
    var addressId=$(elem).parent(".setAddress").parent(".addressItem").attr("data-addressId");
    var userId=$(elem).parent(".setAddress").parent(".addressItem").attr("data-userId");
    $.ajax({
        url:'http://api.qujiamall.com/User/SetDefaultAddress',
        type:'POST',
        data:{
            "address_id":addressId,
            "user_id":userId
        },
        dataType:"JSON",
        async : true,
        success:function(json) {
            setTimeout(function () {
                layer.msg(json.msg);
                //重新请求所有地址刷新
                window.getAllAddress();
            },200)
        }
    });
}
//使用地址
function userAddress(that) {
    $(that).find(".goAddress").show();
    $(that).find(".useBtn").hide();
    $(that).parent().siblings(".addressItem").find(".goAddress").hide();
    $(that).parent().siblings(".addressItem").find(".useBtn").show();
    var addressId=$(that).parent(".addressItem").attr("data-addressid");
    setTimeout(function () {
        //存储选择的地址id
        localStorage.setItem("addressId", addressId);
        window.history.back();
    },500);
}
//删除地址
function deletAddress(that) {
    var _that=that;
    layer.open({
        type: 1,
        title: false,
        shadeClose: true,
        closeBtn:0,
        shade: 0.7,
        maxmin: false, //开启最大化最小化按钮
        area: ['6rem', '3rem'],
        content: $("#popDelete").html(),
        success: function(layero){
            $(".cancelBtn").bind("click",function () {
                layer.closeAll();
            });
            //删除地址
            $(".confirmBtn").bind("click",function () {
                var addressItem=$(_that).parent(".setAddress").parent(".addressItem");
                var addressId=addressItem.attr("data-addressid");
                var userId=addressItem.attr("data-userid");
                $.ajax({
                    url:'http://api.qujiamall.com/User/DeleteAddress',
                    type:'POST',
                    data:{
                        "address_id":addressId,
                        "user_id":userId
                    },
                    dataType:"JSON",
                    async : true,
                    success:function(json) {
                        layer.closeAll();
                        setTimeout(function () {
                            layer.msg(json.msg);
                            //重新请求所有地址刷新
                            window.getAllAddress();
                        },200)
                    }
                });
            })
        }
    });
}